<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="遇见与成长 - 图腾客户管理系统 - {{title}}">
        <title>{{title}}</title>
        <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
        <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
        <link rel="stylesheet" href="/apps/css/mui.css">
    </head>
    <body>
        <header class="d-flex align-items-center bg-custom-color p-3">
            <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
                <i class="fas fa-arrow-left custom-color"></i>
            </button>
            <span class="title-text text-white fs-5">{{excerpt}}</span>
        </header>
        <div id="systemNotification" class="alert alert-info alert-dismissible fade show" role="alert" style="display: none;">
            <!-- 通知内容 -->
            <strong>{{notification}}</strong>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <div class="container">
            <div class="content">

                <div class="row">
                    <div class="col-12">
                        <p>{{{description}}}</p>
                    </div>
                </div>

                <!-- INSERT BODY BEGIN -->

                <div class="row" id="userProfileForm" tabindex="-1" aria-labelledby="userProfileFormLabel" aria-hidden="true">
                    <!-- 输入最新跟进记录的表单 -->
                    <form id="newRecordForm">
                        <div class="row">
                            <div class="col-6">
                                <div class="mb-2">
                                    <label for="view" class="form-label">关联任务</label>
                                    <select class="form-select" id="task_id" name="task_id">
                                        <option value="{{task_id}}">{{task_name}}</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="mb-2">
                                    <label for="view" class="form-label">录入类型</label>
                                    <select class="form-select" id="type" name="type">
                                        <option value="crm-direct_report">直接获取</option>
                                        <option value="crm-proxy_report">间接获取</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-6">
                                <div class="mb-2">
                                    <label for="view" class="form-label">信息分类</label>
                                    <select class="form-select" id="confidentiality" name="confidentiality">
                                        <option value="Confidential">内部查阅</option>
                                        <option value="Unclassified">公开信息</option>
                                        <option value="Secret">需要审批</option>
                                        <option value="TopSecret">保密资料</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="mb-2">
                                    <label for="attachment" class="form-label">附件</label>
                                    <input type="file" class="form-control" id="attachment" multiple onchange="uploadFiles(this.files)">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="mb-2">
                                <label for="uploadedFiles" class="form-label">已传附件</label>
                                <ul id="uploadedFilesList" class="list-unstyled"></ul>
                            </div>
                        </div>
                        <div class="row">
                            <div class="mb-2">
                                <label for="memo" class="form-label">输入最新的跟进记录</label>
                                <textarea class="form-control" id="memo" rows="3"></textarea>
                            </div>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="addUserProfile({{uid}})">添加记录</button>
                    </form>

                </div>

                <!-- 在这里显示用户档案记录 -->
                <div class ="row">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>来源</th>
                                    <th>内容</th>
                                    <!-- 添加其他需要显示的列 -->
                                </tr>
                            </thead>
                            <tbody id="userProfileRecords">
                                {{#each profiles}}
                                <tr data-id="{{this.id}}" onclick="">
                                    <td class="cell-content" width="25%">
                                        <small>{{{this.type}}} {{{this.atype}}}#{{{this.aid}}}<br><span style='color:#c1c1c1'>{{{this.created_at}}} #{{this.id}}</span></small>
                                    </td>
                                    <td class="cell-content">
                                        <small>{{{this.memo}}}</small><br>
                                        <small>{{{this.attachments_link}}}</small>
                                    </td>
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- INSERT BODY END-->

                <nav aria-label="Page navigation" class="pagination-container">
                    <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
                        <i class="fas fa-home" style="color:white;"></i>
                    </button>
                    <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="searchInPage();">
                        <i class="fas fa-search" style="color: white;"></i>
                    </button>
                    <ul class="pagination">
                        {{{paginator}}}
                    </ul>
                </nav>

            </div>
        </div>

        <!-- Footer with Back Button and Search Button -->
        <footer class="footer" style="text-align: center;">
            <div class="row">
                <div class="text-muted">&nbsp;</div>
                <div class="text-muted">&nbsp;</div>
                <div class="text-muted">&copy;2023 图腾生命医学</div>
                <div class="text-muted">我们为人类免疫事业而奉献</div>
            </div>
        </footer>

        <!-- JavaScript scripts -->
        <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
        <script src="/apps/js/bootstrap.bundle.min.js"></script>
        <script src="/apps/js/crm-hbs-utils.js"></script>
        <script src="/apps/js/wx-client-dom.js"></script>

        <script>
        const totemUID = parseInt("{{totemUID}}") || 0;
        let attachmentUrls = []; // 在适当的地方定义
        let selectedFileNames = [];

        function clearUserProfilesInput() {
            // 清空表单内容
            const formInputs = document.querySelectorAll('#userProfileForm input, #userProfileForm textarea');
            formInputs.forEach(input => { input.value = ''; });
            attachmentUrls = []; // 在适当的地方定义
            selectedFileNames = [];
            // 获取已上传文件列表容器
            const uploadedFilesList = document.getElementById('uploadedFilesList');
            // 清空已上传文件列表
            uploadedFilesList.innerHTML = '';
        };

        async function addUserProfile(uid) {

            const memo = document.getElementById('memo').value;
            const type = document.getElementById('type').value;
            const task_id = document.getElementById('task_id').value;
            const confidentiality = document.getElementById('confidentiality').value;

            if (!memo || memo == '' || memo.length < 5 ) {
				showSystemNotification("请提交有意义的跟进记录", 'error');
                return false;
			};

			const attachment = document.getElementById('attachment').files;
			try {
				const response = await fetch('/apps/api/user-profile', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ uid, memo, type, attachmentUrls, confidentiality, task_id })
				});

				if (response.ok) {

					const userProfileRecords = document.getElementById('userProfileRecords');
					const title = `${type} user#${uid}`;
					const current = (new Date()).toLocaleString('en-US').replace(/\//g, '-');

					let attachments_link = '';
					attachmentUrls.forEach((url, index) => {
						const fileName = selectedFileNames[index]; // 获取对应文件的本地名称
						attachments_link += `<span><a href="#" onclick="openFile('${url}', '${fileName}')">${fileName} </a></span>`;
					});

					const recordHTML = `
						<tr>
						<td><small>${title}<br><span style='color:#c1c1c1'>${current}</span></small></td>
						<td><small>${memo}<br>${attachments_link}</small></td>
						<!-- 根据需要添加其他列 -->
						</tr>
						`;
					// 显示插入新记录
					userProfileRecords.insertAdjacentHTML('afterbegin', recordHTML);
					showSystemNotification("小伙伴，大功告成！新记录已成功添加", 'success');
					clearUserProfilesInput();
				} else {
					showSystemNotification("添加记录失败，请稍后再试", 'error'); // 错误通知
				}
			} catch (error) {
				console.error('Error:', error);
				showSystemNotification("添加记录失败，请稍后再试", 'error'); // 错误通知
			}
        }

        async function uploadFiles(files, code='assifiedddUserProfile') {
            const formData = new FormData();
            formData.append('uid', totemUID);
            formData.append('code', code);
            let fileName = 'UNTITLED';
            Array.from(files).forEach((file) => {
                formData.append('file', file);
                fileName = file.name;
            });
            const uploadUrl = 'https://mall.totembio.cn/api/uploadMtaFile'; // 后端文件传接口地址
            const response = await fetch(uploadUrl, {
                method: 'POST',
                body: formData,
            });
            if (response.ok) {
                const responseData = await response.json();
                const uploadedSrc = responseData?.data?.src;
                attachmentUrls.push(uploadedSrc); // 将上传成功的附件链接保存到 attachmentUrls 数组中
                selectedFileNames.push(fileName); // 记录所选文件的名称
                showUploadedFilesList();
            } else {
                alert('文件上传失败！');
            }
        }

        function showUploadedFilesList() {
            // 获取已上传文件列表容器
            const uploadedFilesList = document.getElementById('uploadedFilesList');
            // 清空已上传文件列表
            uploadedFilesList.innerHTML = '';
            // 填充已上传文件链接到列表中
            attachmentUrls.forEach((url, index) => {
                const listItem = document.createElement('li');
                const fileName = selectedFileNames[index]; // 获取对应文件的本地名称
                listItem.innerHTML = `
                    <span><a href="#" onclick="openFile('${url}', '${fileName}')">${fileName}</a></span>
                    <span style="color: red; cursor: pointer;" onclick="removeAttachment(${index})">删除附件</span>
                    `;
                uploadedFilesList.appendChild(listItem);
            });
        }

        function openFile(url, fileName) {
            const fileURL = `${url}`; // 构建完整的文件 URL
            const newWindow = window.open(fileURL, '_blank');
            if (newWindow) {
                newWindow.document.write(`<html><head><title>${fileName}</title></head><body><h1>${fileName}</h1><iframe src="${fileURL}" style="width:100%; height:100vh;"></iframe></body></html>`);
            } else {
                alert('请允许弹出窗口以查看文件');
            }
        }

        // 新增移除已上传文件链接的函数
        function removeAttachment(index) {
            // 从 attachmentUrls 数组中移除指定索引的链接
            attachmentUrls.splice(index, 1);
            selectedFileNames.splice(index, 1);
            showUploadedFilesList();
        }

        function searchInPage() {
            let searchText = window.prompt("请输入内容，匹配部分将被高亮显示", "");
            if (searchText && window.find && window.getSelection) {
                document.designMode = "on";
                var sel = window.getSelection();
                sel.collapse(document.body, 0);
                while (window.find(searchText)) {
                    document.execCommand("HiliteColor", false, "#88b04b"); // 高亮显示匹配项
                    sel.collapseToEnd();
                }
                document.designMode = "off";
            }
        }

        function showSystemNotification(message, type='info' ) {
            if ( !message || message == '') return;
            const systemNotification = document.getElementById('systemNotification');
            const notificationContent = systemNotification.querySelector('.alert strong');

            notificationContent.textContent = message; // 更新通知内容
			// 根据类型设定通知样式
			if (type === 'success') {
				systemNotification.classList.remove('alert-danger'); // 移除错误样式
				systemNotification.classList.add('alert-success'); // 添加成功样式
			} else if (type === 'error') {
				systemNotification.classList.remove('alert-success'); // 移除成功样式
				systemNotification.classList.add('alert-danger'); // 添加错误样式
			}

            systemNotification.style.display = 'block'; // 显示通知

            setTimeout(() => {
                systemNotification.style.display = 'none'; // 5秒后隐藏通知
            }, 8000);
        }

        showSystemNotification("{{notification}}");

        </script>

    </body>
</html>

